const url = 'http://127.0.0.1:3000';
//const url = 'http://39.108.158.235/';
let socket = null;

let _username = '';
let _$username = $('#username');
let _$loginButton = $('#loginbutton');
let _$inputText = $('#inputText');
let _$sendButton = $('#sendbutton');
let _$closeButton = $('#closebutton');

let isUserLogined = () => {
    _username = $.cookie('username');
    if (_username) {
        socket = io.connect(url);
        socket.emit('login', { username: _username });
        onSocket(socket);
    } else if (socket) {
        //如果cookie失效，则断开连接
        socket.disconnect();
    }
}
let loginAction = () => {
    _username = _$username.val().trim();
    if (_username) {
        $.post('/login', { username: _username })
            .done((res) => {
                if (res.success) {
                    socket = io.connect(url);
                    socket.emit('login', { username: _username});
                    onSocket(socket);
                } else {
                    alert("该用户已登录！");
                }                  
            });
    } else {
        alert("请输入用户名！");
    }
}

let sendMessage = () => {
   let _message = _$inputText.val();
   if (_message) {
       socket.emit('sendMessage', {username: _username, message: _message});
       _$inputText.val('');
   } else {
       alert("请输入发送消息！");
   }
}

let showMessage = (data) => {
    if (data.username === _username) {
        $('#chatBodyBox').append(`<div class='self-message'><span class='self-msg msg'>${data.message}</span></div>`);
    } else {
        $('#chatBodyBox').append(`<div class='other-message'><span class=‘name’>${data.username}: </span><span class='other-msg msg'>${data.message}</span></div>`);
        $("#newMessage")[0].src = "static/newMessage.wav";
        $("#newMessage")[0].play();
    }
    $("#chatBodyBox").scrollTop($("#chatBodyBox")[0].scrollHeight);
}

let showChatWindow = () => {
    changeWindow(true);  
}
let showUsers = (data) => {
    $('#userListBox').empty();
    $('#userListBox').append(`<h6>当前在线人数：${data.usersNum}</h6>`);
    $('#userListBox').append('<ul id="userList" class="userList"></ul>');
    if (data.users) {
        $('#userList').append(data.users.map((user) => `<li>${user.username}</li>`).join(''))
    }
}
let logout = () => {

    if (confirm("确定要离开？")){
        $.cookie("username", null, { expires: -1 });
        socket.emit('logout', { username: _username }); 
        socket.disconnect();
        changeWindow(false);
    }
}
let changeWindow = (isLogined) => {
    if (isLogined) {
        $('#chatWindow').show('slow');
        $('#login').hide('slow');
        _$inputText.focus();
    } else {
        $('#chatWindow').hide('slow');
        $('#login').show('slow');
        _$username.focus();
    }
}

/**前端事件 */
_$loginButton.on('click', (event) => {
    loginAction();
})

_$sendButton.on('click', (event) => {
    sendMessage();
})

_$closeButton.on('click', (event) => {
    logout();
})
_$username.on('keyup', (event) => {
    if (event.keyCode === 13) {
        loginAction();
    }
})
_$inputText.on('keydown', (event) => {
    if (event.ctrlKey && event.keyCode == 13) {
        sendMessage();
    }
})
$(window).on('load', () => {
    _$username.focus();
    isUserLogined();
})
/** 
 * $(window).on('beforeunload', (e) => {})
 * 由于很多手机浏览器会忽略该事件，且该事件触发的函数内部默认block confirm, prompt, alert等函数，所以决定不使用该事件
 */
/**socket */

let onSocket = (socket) => {
    socket.on('loginResult', (data) => {
        if (data.code === 0) {
            showChatWindow();
            showUsers(data);
            if (data.loginUser) {
                $("#user")[0].src = "static/user.wav";
                $("#user")[0].play();
                $('#chatBodyBox').append(`<div class='loginout-msg'>${data.loginUser} 进入了聊天室...</div>`);
                $("#chatBodyBox").scrollTop($("#chatBodyBox").scrollHeight);
            }
        } else {
            alert("登录失败！");
        }
    });
    socket.on('receiveMessage', (data) => {
        showMessage(data);
    });
    socket.on('logoutResult', (data) => {
        if (data.users) {
            showUsers(data);
        };
        if (data.logoutUser) {
            $("#user")[0].src = "static/user.wav";
            $("#user")[0].play();
            $('#chatBodyBox').append(`<div class='loginout-msg'>${data.logoutUser} 离开了聊天室...</div>`);
            $("#chatBodyBox").scrollTop($("#chatBodyBox").scrollHeight);
        }
    })
}

